package com.itheima.web.controller.manufacturer;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.cargo.Factory;
import com.itheima.domain.cargo.FactoryExample;
import com.itheima.service.cargo.FactoryService;
import com.itheima.web.controller.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.UUID;

@Controller
@RequestMapping("/manufacturer/factory")
public class FactoryController extends BaseController {
    @Reference
    private FactoryService factoryService;

    @RequestMapping(value = "/list", name = "厂家信息查询")
    public String list(
            @RequestParam(defaultValue = "1", name = "page") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        FactoryExample factoryExample = new FactoryExample();
        PageInfo pageInfo = factoryService.findByPage(pageNum, pageSize, factoryExample);
        request.setAttribute("page", pageInfo);
        return "/manufacturer/factory/factory-list";
    }

    @RequestMapping(value = "/toAdd", name = "跳转厂家新增页面")
    public String toAdd() {
        return "/manufacturer/factory/factory-add";
    }

    @RequestMapping(value = "/toUpdate", name = "跳转厂家编辑页面")
    public String toUpdate(String id) {
        //1. 根据id查询当前厂家信息
        Factory factory=factoryService.findById(id);
        request.setAttribute("factory", factory);

        //2. 转发到修改页面
        return "/manufacturer/factory/factory-update";
    }

    @RequestMapping(value = "/edit", name = "厂家新增")
    public String edit(Factory factory){
        if (StringUtils.isEmpty(factory.getId())){
            //1.设置主键
            factory.setId(UUID.randomUUID().toString());

            //2.设置厂家信息
            factory.setCreateBy(getUser().getId());
            factory.setCreateDept(getUser().getDeptId());
            //3.创建时间
            factory.setCreateTime(new Date());

            factoryService.save(factory);
        }else{

            factoryService.update(factory);

        }
        //重定向到list方法
        return "redirect:/manufacturer/factory/list.do";
    }
    @RequestMapping(value = "/delete", name = "厂家删除")
    public String delete(String id) {
        //调用service删除
        factoryService.delete(id);
        //重定向到list方法
        return "redirect:/manufacturer/factory/list.do";
    }

}
